package mwt.xml.xdbforms.schemalayer.types;

import javax.xml.XMLConstants;
import mwt.xml.xdbforms.dblayer.metadata.impl.ColumnMetaData;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;

/**
 * Mappa il tipo Text sql con un Text xschema
 * @author Gianfranco Murador, Matteo Ferri, Cristian Castiglia
 */
public class XmlText extends XmlTypes {

    public XmlText() {
    }

    public XmlText(Document doc) {
        super(doc);
    }

    private void buildFragment(ColumnMetaData cmd) {

        Element xtype, restriction, maxLength;
        fragment = doc.createDocumentFragment();
        xtype = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:simpleType");
        xtype.setAttribute("name", typeName);
        restriction = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:restriction");
        restriction.setAttribute("base", "xs:string");
        cmd.setXschemaTypeName(typeName);

        maxLength = doc.createElementNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "xs:maxLength");
        maxLength.setAttribute("value", cmd.getDisplaySize().toString());

        xtype.appendChild(restriction);
        restriction.appendChild(maxLength);
        fragment.appendChild(xtype);


    }

    @Override
    public DocumentFragment getSchemaType(ColumnMetaData cmd) {

        typeName = cmd.getTypeName();

        if (typeName.equals("LONGTEXT") || typeName.equals("TEXT") || typeName.equals("MEDIUMTEXT")) {

            buildFragment(cmd);
            return fragment;
        } else {

            return nextType.getSchemaType(cmd);
        }


    }

    @Override
    public Object getXSchemaToJavaType(String baseType, String value) {

        if (baseType.startsWith("LONGTEXT") || baseType.startsWith("TEXT") || baseType.startsWith("MEDIUMTEXT")) {

            return value;
            
        } else {
            return nextType.getXSchemaToJavaType(baseType, value);
        }


    }
}

